<script setup lang="ts">
  import { computed, PropType, ref, watch } from 'vue'
  import { v4 as uuidv4 } from 'uuid'
  import { initWebSocket } from '@/utils/socket'
  import {
    syncCustomerFromSAP,
    syncGoodListFromSAP,
    syncSaleAmountFromSAP,
    syncSnCodeFromSAP,
  } from '@/api/store'
  import { SyncMode } from '../types'
  import moment from 'moment'
  import { HMessageBox } from '@/components/common/message'

  defineOptions({
    name: 'SyncModal',
  })

  const props = defineProps({
    type: {
      type: String as PropType<SyncMode>,
      required: true,
    },
  })

  const visible = defineModel<boolean>('modelValue', { default: false })
  const progreeDialogVisible = ref(false)

  const syncMsg = ref<{
    currentProgress: string
    end: boolean
    importFailtDataList: Array<string>
    message: string
    totalCount: number
  }>({
    currentProgress: '0',
    end: false,
    importFailtDataList: [],
    message: '',
    totalCount: 0,
  })

  const form = ref<{ dateRange: Array<string> }>({
    dateRange: [],
  })

  const topLeftTitle = computed(() => {
    if (props.type === 'sn-code') {
      return '同步条码信息'
    }

    if (props.type === 'customer') {
      return '同步客户信息'
    }

    if (props.type === 'spare-part') {
      return '同步物料信息'
    }

    if (props.type === 'sale-amount') {
      return '同步销售金额'
    }

    return ''
  })

  const hideDialog = () => {
    visible.value = false
    form.value.dateRange = ['', '']
  }

  const funProgress = (msg: {
    currentProgress: string
    end: boolean
    importFailtDataList: Array<string>
    message: string
    totalCount: number
  }) => {
    syncMsg.value = msg
  }

  const onSubmitClick = async () => {
    try {
      const uuid = uuidv4()
      initWebSocket(funProgress, `/ws/progress/${uuid}`)
      let res: null | APIResponse = null
      const startDate =
        form.value.dateRange && form.value.dateRange[0] ? form.value.dateRange[0] : ''
      const endDate = form.value.dateRange && form.value.dateRange[1] ? form.value.dateRange[1] : ''
      if (props.type === 'sn-code') {
        res = (await syncSnCodeFromSAP({ startDate, endDate }, uuid)).data
      }
      if (props.type === 'spare-part') {
        res = (await syncGoodListFromSAP({ startDate, endDate }, uuid)).data
      }
      if (props.type === 'customer') {
        res = (await syncCustomerFromSAP({ startDate, endDate }, uuid)).data
      }
      if (props.type === 'sale-amount') {
        res = (await syncSaleAmountFromSAP({ startDate, endDate }, uuid)).data
      }
      if (res) {
        if (res.code === 20000) {
          progreeDialogVisible.value = true
          visible.value = false
        } else {
          HMessageBox.error(res.message)
        }
      } else {
        HMessageBox.error('同步失败，请稍后重试')
      }
    } catch (error) {
      HMessageBox.error('同步失败，请稍后重试')
    }
  }

  watch(visible, (value) => {
    if (value) {
      form.value.dateRange = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
    }
  })
</script>

<template>
  <div>
    <!-- 同步设置弹窗 -->
    <h-dialog v-model="visible" :title="topLeftTitle" @close="hideDialog">
      <el-form label-position="top" inline-message class="modal_form_content">
        <el-form-item label="同步时间范围">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="到"
            unlink-panels
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <h-button is-modal type="primary" @click="onSubmitClick">开始同步</h-button>
        <h-button is-modal @click="hideDialog">取消</h-button>
      </template>
    </h-dialog>

    <!-- 进度条弹窗 -->
    <h-dialog v-model="progreeDialogVisible" :title="topLeftTitle" is-hide-close>
      <div class="synchronization-progress-wrapper">
        <el-progress
          v-if="!syncMsg.end && syncMsg.currentProgress !== '100'"
          :stroke-width="10"
          type="circle"
          :percentage="Number(syncMsg.currentProgress)"
          color="#00c0c0"
          class="synchronization-progress"
        >
          <div class="progress-content">
            <div class="num"> {{ Number(syncMsg.currentProgress).toFixed(2) }}% </div>
            <div class="tip">正在同步数据，请稍等...&nbsp;...</div>
          </div>
        </el-progress>
        <div
          v-if="
            (syncMsg.end || syncMsg.currentProgress === '100') &&
            syncMsg.importFailtDataList.length === 0
          "
          class="success-wrapper"
        >
          <div class="circle">
            <i class="iconfont icon-dagou"></i>
          </div>
          <div class="tip">数据同步成功，共同步{{ syncMsg.totalCount }}条数据</div>
        </div>
        <div
          v-if="
            (syncMsg.end || syncMsg.currentProgress === '100') &&
            syncMsg.importFailtDataList.length > 0
          "
          class="fail-wrapper"
        >
          <div class="circle-bg">
            <div class="circle">
              <i class="iconfont icon-guanbi"></i>
            </div>
          </div>
          <div ref="msgContentBoxs" class="msg-wrapper">
            {{ syncMsg.message }}
          </div>
        </div>
      </div>

      <template #footer>
        <h-button
          v-if="syncMsg.end || syncMsg.currentProgress === '100'"
          is-modal
          @click="progreeDialogVisible = false"
        >
          关闭
        </h-button>
      </template>
    </h-dialog>
  </div>
</template>

<style scoped lang="scss">
  :deep(.el-date-editor) {
    height: 26px;
    width: 100%;
  }

  .synchronization-progress-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 480px;
    justify-content: center;
    row-gap: 12px;

    .synchronization-progress {
      :deep(.el-progress-circle) {
        width: 300px !important;
        height: 300px !important;
      }

      :deep(.el-progress__text) {
        .progress-content {
          display: flex;
          flex-direction: column;
          row-gap: 8px;

          .num {
            font-size: 32px !important;
          }

          .tip {
            font-size: 16px;
            color: #777;
          }
        }
      }
    }

    .success-wrapper {
      display: flex;
      flex-direction: column;
      row-gap: 8px;
      align-items: center;

      .circle {
        width: 200px;
        height: 200px;
        border-radius: 300px;
        background-color: #f5f5f5;
        display: flex;
        justify-content: center;
        align-items: center;

        .iconfont {
          font-size: 128px;
          color: $secondColor3;
        }
      }

      .tip {
        text-align: center;
        font-size: 24px;
      }
    }

    .fail-wrapper {
      display: flex;
      flex-direction: column;
      height: 100%;
      align-items: center;
      row-gap: 12px;

      .circle-bg {
        height: 240px;
        display: flex;
        align-items: center;

        .circle {
          width: 200px;
          height: 200px;
          border-radius: 300px;
          background-color: #f5f5f5;
          display: flex;
          justify-content: center;
          align-items: center;

          .iconfont {
            font-size: 128px;
            color: $deleteColor;
          }
        }
      }

      .msg-wrapper {
        display: flex;
        flex-direction: column;
        height: 200px;
        overflow: auto;
        align-items: center;
        justify-content: flex-start;
        width: 600px;
      }
    }
  }
</style>
